package a66weding.com.jiehuntong.activity.me;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.alipay.PayResult;
import a66weding.com.jiehuntong.alipay.SignUtils;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ALiOrderSingBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.OrderResultBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.wx.PayActivity;

/**
 * 这是支付界面
 * Created by Administrator on 2016/7/29.
 */
public class MePayActivity extends MeBaseActivity implements View.OnClickListener ,OnNetResultListener{
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mRightTitleTv;
    private Button mPayBt;
//    private String mTotalPrice;//商品支付总价格
    private TextView mGoodsTotalPrice;//显示订单金额

    private OrderResultBean.DataBean orderResultBean;

    private static final int TOTALPARERR=10;

    //微信支付
    private LinearLayout zhifu_wx;
    private static final int ALIPAY=5;
    private boolean isCanAliPay;
    private boolean isMoneyRight=true;


    /**
     * 以下这些在服务器处理，不能暴露在代码中
     */
    // 商户PID
    public static final String PARTNER = "2088121601543342";
    // 商户收款账号
    public static final String SELLER = "cnbearbaby@qq.com";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "";
    // 支付宝公钥
    public static final String RSA_PUBLIC = "";
    private static final int SDK_PAY_FLAG = 1;

    private String orderNumber;
    private int memberId;
    private String substring;
    private ALiOrderSingBean aLiOrderSingBean =null;

    private float totalPayMoney;
    private boolean isFromMyOrder;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();

                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(MePayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.putExtra("totalPay",aLiOrderSingBean.getTotalPrice());
                        intent.putExtra("orderNumber",orderNumber);
                        intent.setClass(MePayActivity.this, MePaySucceedActivity.class);
                        startActivity(intent);

                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(MePayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(MePayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            isCanAliPay=true;

                        }
                    }
                    break;
                }
                case ALIPAY:
                        isCanAliPay=true;
                    break;
                case TOTALPARERR:
                    isMoneyRight=false;
                    break;
                default:
                    break;
            }
        }


    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_pay);
       EventBus.getDefault().register(this);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MePayActivity", this);

        Intent intent = getIntent();
        if(intent!=null) {
            Bundle extras = intent.getExtras();
            isFromMyOrder = intent.getBooleanExtra("isFromMyOrder", false);
            //购物车;
            if(extras!=null && !isFromMyOrder) {
                orderResultBean = (OrderResultBean.DataBean) extras.get("order");
                totalPayMoney = StrUtil.floatNumDeal((float) (orderResultBean.getOrder().getDm_TotalMoney()));
                orderNumber = orderResultBean.getOrder().getOrderNumber();
            }
            //去支付界面 WaitpayOrder;
            if(isFromMyOrder) {
                orderNumber = intent.getStringExtra("ordersNumber");
                totalPayMoney =  intent.getFloatExtra("newPayMoney",0.0f);
                orderResultBean = new OrderResultBean.DataBean();
                OrderResultBean.DataBean.OrderBean orderBean = new  OrderResultBean.DataBean.OrderBean();
                orderBean.setOrderNumber(orderNumber);
                orderBean.setDm_TotalMoney(totalPayMoney);
                orderResultBean.setOrder(orderBean);
            }


        }

        if(((GlobalApplication)getApplication()).isLogin()) {

            memberId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        }
        initview();

        initdata();
    }



    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.lay_head_backlay);
        mBackContentTv = (TextView) findViewById(R.id.headleft_title_tv);
        mHeaderTitleTv = (TextView) findViewById(R.id.headcenter_title_tv);
        mRightTitleTv = (TextView) findViewById(R.id.headright_title_tv);
        mPayBt = (Button) findViewById(R.id.btn_add);
        mGoodsTotalPrice = (TextView) findViewById(R.id.tv_goods_totalPrice);

        zhifu_wx  = (LinearLayout) findViewById(R.id.zhifu_wx);
        zhifu_wx.setOnClickListener(this);
        mGoodsTotalPrice.setText(""+totalPayMoney);
        mBackContentTv.setText("订单");
        mHeaderTitleTv.setText("在线支付");
        mRightTitleTv.setVisibility(View.GONE);

        mBackLay.setOnClickListener(this);
        mPayBt.setOnClickListener(this);
    }


    private void initdata() {

        String url= RequestCode.get_AlipayKeyValidate;

        url += "&orderNumber="+orderNumber+"&memberID="+memberId;

        RequestParams requestParams = new RequestParams(url);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(!TextUtils.isEmpty(result)) {
                    int serviceIndex = result.indexOf("service");
                    int totalPriceIndex = result.indexOf("TotalPrice");

                    substring = result.substring(serviceIndex, totalPriceIndex - 3);

                    try {
                        Gson gson = new Gson();

                        aLiOrderSingBean = gson.fromJson(result, ALiOrderSingBean.class);
                        String totalPrice = aLiOrderSingBean.getTotalPrice();
                        Float aFloat = Float.valueOf(totalPrice);

                        if(!( aFloat.floatValue() == totalPayMoney)) {
                            CUtils.showToast("数据校验失败，请重新生成订单！");
                            mHandler.sendEmptyMessage(TOTALPARERR);
                            return;
                        }

                        mHandler.sendEmptyMessage(ALIPAY);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {


            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_head_backlay: //点击订单，返回到上一级界面
                finish();
                break;
            case R.id.btn_add: //支付
                if(isCanAliPay) {
                    if(!isMoneyRight) {
                        CUtils.showToast("数据校验失败，请重新选择订单！");
                        return;
                    }
                    pay();
                    isCanAliPay=false;
                }else{
                    CUtils.showToast("数据校验失败，请重新选择订单！");
                }

                break;
            case R.id.zhifu_wx://微信支付;
                    //判断是否安装了微信
                    boolean bo = Tools.isAppInstalled(this,"com.tencent.mm");
                    if (bo){
                        Intent intent = new Intent(this, PayActivity.class);
                        intent.putExtra("order",orderResultBean);
                        intent.putExtra("subject",aLiOrderSingBean.getData());
                        startActivity(intent);
                    }else{
                        CUtils.showToast("请先安装微信客户端");
                    }
 //               }
                break;
        }
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay() {

        final String payInfo =aLiOrderSingBean.getData();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(MePayActivity.this);

                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };


        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }



    private String out_trade_no="B16082911342066";

    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(String subject, String body, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + out_trade_no+ "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + Url.SURL + "/WeddingMobileApi/AlipayBackUrlAction" + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {

    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(MessageEvent event) {
        if (event.getPayCode()==0){

        }
    }

    /**
     * POST WeddingMobileApi/WXPayTrueSendMsg?Token={Token}&out_trade_no={out_trade_no}&alipayJinE=
     * {alipayJinE}&wxPass={wxPass}&buyer_id={buyer_id}
     * &gmt_payment={gmt_payment}&trade_no={trade_no}&trade_status={trade_status}
     wx pay back
     */
    private void getWXPayTrueSendMsg(){

    }
}
